#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

import sys

from common.parse_parafile import ParamFileUtil

from common.common import exter_attack
from common.const import SysData
from exchange import log
from exchange.commons.common import output_result_file
from exchange.commons.const import ExchangeJobInfo, SubJobPolicy, SubJobPriorityEnum
from exchange.commons.exchange_exception import ExchangeErrCodeException
from exchange.commons.exchange_function_tool import log_start_end
from exchange.commons.exchange_param_parse import ExchangeParamParse
from exchange.restore.restore_base.base_exchange_restore_gen_sub_job import ExchangeRestoreGenSubJob



class DagRestoreGenSubJob(ExchangeRestoreGenSubJob):
    def __init__(self, thread_pid, param):
        super().__init__(thread_pid, param)
        self._pid = thread_pid

    @log_start_end()
    def do_gen_sub_job_task(self, job_info: ExchangeJobInfo):
        """
        Dag 任务拆分子任务
        :param job_info: 框架下发参数
        :return:成功 true，失败 false
        """
        nodes = self._param.get("job").get("targetEnv").get("nodes")
        response = []
        for node in nodes:
            node_id = node['id']
            job_policy = SubJobPolicy.FIXED_NODE.value
            job_name = node["name"]
            job_priority = SubJobPriorityEnum.JOB_PRIORITY_1.value
            response.append(self.build_sub_job(job_priority, job_policy, job_name, node_id, job_info))
        output_result_file(job_info.pid, response)
        return True


@exter_attack
def do_exec(thread_pid, task_job_id, task_sub_job_id):
    try:
        param = ParamFileUtil.parse_param_file(thread_pid)
        job = DagRestoreGenSubJob(thread_pid, param)
        job.do_gen_sub_job_task(
            ExchangeParamParse.get_restore_job_info(thread_pid, task_job_id, task_sub_job_id, param))
    except ExchangeErrCodeException as err_str:
        log.error(f"Restore gen sub job failed, err: {err_str}, pid:{pid}")
        return False
    return True

if __name__ == '__main__':
    for line in sys.stdin:
        SysData.SYS_STDIN = line
        break

    if len(sys.argv) < 1:
        log.error("Param is wrong.")
        sys.exit(1)

    args_list = sys.argv[1:]
    log.info(f"get args_list: {args_list}")
    pid = args_list[0]
    job_id = ""
    sub_job_id = ""
    if len(args_list) >= 2:
        job_id = args_list[1]
    if len(args_list) == 3:
        sub_job_id = args_list[2]
    try:
        do_exec(pid, job_id, sub_job_id)
    except Exception as err:
        log.error(f"Err: {err}, pid: {pid}")
        sys.exit(0)

    sys.exit(0)
